package com.guxuede.mina.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.apache.mina.core.buffer.IoBuffer;

public class FileUtil {

	public static IoBuffer getFileContent(String filename) {
		File f = new File("webroot/" + filename);
		FileInputStream in = null;
		IoBuffer buffer = null;

		try {
			in = new FileInputStream(f);
		} catch (FileNotFoundException e) {
			try {
				in = new FileInputStream("webroot/404.html");
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}

		buffer = IoBuffer.allocate(1024).setAutoExpand(true);
		byte[] b = new byte[1024];
		int l = -1;
		try {
			while ((l = in.read(b)) != -1) {
				buffer.put(b, 0, l);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return buffer;
	}
	
	public static IoBuffer getFile(String filename) {
		File f = new File("webroot/" + filename);
		FileChannel in=null;
		try {
			in = new FileInputStream(f).getChannel();
		} catch (FileNotFoundException e) {
			try {
				in = new FileInputStream("webroot/404.html").getChannel();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		
		IoBuffer ioBuffer=IoBuffer.allocate(1024).setAutoExpand(true);
		ByteBuffer buffer = ByteBuffer.allocate(1024); 
		try {
			while(in.read(buffer)!=-1){
				ioBuffer.put(buffer);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ioBuffer;
	}
	
	public static IoBuffer getFileIoBuffer(String filename){
		File file = new File("webroot/" + filename);
		FileChannel fc=null;
		try {
			fc = new FileInputStream(file).getChannel();
		} catch (FileNotFoundException e) {
			try {
				fc = new FileInputStream("webroot/404.html").getChannel();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		ByteBuffer buffer=null;
		try {
			buffer=fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(buffer);
		try {
			if(fc!=null)fc.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return IoBuffer.wrap(buffer);
	}
	
}
